package org.gongliang.common.task;

import java.lang.reflect.Method;

import org.apache.log4j.Logger;
import org.gongliang.entity.sys.Task;
import org.gongliang.kit.str.StrKit;

/**
 * @description 定时任务工具类
 * @author 龚亮
 * @date 2015-05-27 14:22:13
 */
public class TaskKit {

	public final static Logger logger = Logger.getLogger(TaskKit.class);

	/**
	 * 通过反射调用scheduleJob中定义的方法
	 * 
	 * @param scheduleJob
	 */
	public static void invokMethod(Task schedule) {
		Object object = null;
		Class<?> clazz = null;
		if (StrKit.notBlank(schedule.getBeanClass())) {
			try {
				clazz = Class.forName(schedule.getBeanClass());
				object = clazz.newInstance();
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}

		}
		if (object == null) {
			logger.error("任务名称 = [" + schedule.getJobName() + ",任务=" + schedule.getBeanClass() + "."
					+ schedule.getMethodName() + "]---------------未启动成功，请检查是否配置正确！！！");
			return;
		}
		clazz = object.getClass();
		Method method = null;
		try {
			method = clazz.getDeclaredMethod(schedule.getMethodName());
		} catch (NoSuchMethodException e) {
			logger.error("任务名称 = [" + schedule.getJobName() + ",任务=" + schedule.getBeanClass() + "."
					+ schedule.getMethodName() + "]---------------未启动成功，方法名设置错误！！！");
		} catch (SecurityException e) {
			logger.error(e.getMessage(), e);
		}
		if (method != null) {
			try {
				method.invoke(object);
			} catch (Exception e) {
				logger.error(e.getMessage(), e);
			}
		}
		logger.debug("任务名称 = [" + schedule.getJobName() + ",任务=" + schedule.getBeanClass() + "."
				+ schedule.getMethodName()
				+ "]----------启动成功");
	}
}
